const connect = require('gulp-connect')
const webpack = require('webpack-stream')
const sass    = require('gulp-sass')
const proxy   = require('http-proxy-middleware')
const del     = require('del')  

const{src,series,parallel,dest,watch} = require("gulp")

function packHtml(){
    return src('../src/*.html')
        .pipe(dest('../dev'))
        .pipe(connect.reload())
}

function packAssets(){
    return src('../src/assets/**/*')
        .pipe(dest('../dev/assets'))
        .pipe(connect.reload())
}
// 拷贝字符串模板插件
function packLibs(){
    return src('../src/libs/**/*')
        .pipe(dest('../dev/libs'))
        .pipe(connect.reload())
}

function packCss(){
    return src('../src/styles/*.scss')
        .pipe(sass().on('error',sass.logError))
        .pipe(dest('../dev/styles'))
        .pipe(connect.reload())
}


function packJs(){
    return src('../src/scripts/main.js')
        .pipe(webpack({
            mode:'development',
            entry:{
                main:'../src/scripts/main.js',
                starpage:'../src/scripts/starpage.js'
            },
            output :{
                filename:'[name].js'
            },
            module: {
                rules: [
                  {
                    test: /\.m?js$/,
                    exclude: /(node_modules|bower_components)/,
                    use: {
                      loader: 'babel-loader',
                      options: {
                        presets: ['@babel/preset-env'],
                        plugins: ['@babel/plugin-transform-runtime']
                      }
                    }
                  },
                  {
                    test: /\.html$/,
                    loader: 'string-loader'
                  }
                ]
              }
        }))
        .pipe(dest('../dev/scripts'))
        .pipe(connect.reload())
}


function delDevFile(){
    return del('../dev/**', {
        force: true
      })
}


function webServer(){
    return connect.server({
        root : '../dev',
        host : '10.60.15.31',
        port:8886,
        livereload:true,
        middleware:function(){
            return [
                proxy('/dm',{
                    target:'https://search.damai.cn',
                    changeOrigin:true,
                    pathRewrite :{
                        '^/dm':''
                    }
                })
            ]
        }
    })
}

function watcher(){
    watch('../src/styles/**/*.scss',packCss);
    watch('../src/*.html',packHtml);
    watch('../src/scripts/**/*',packJs);
    watch('../src/assets/**/*',packAssets);
    watch('../src/libs/**/*',packLibs);
}

exports.default = series(delDevFile,packCss,packJs,parallel(packHtml,packAssets,packLibs),parallel(watcher,webServer));